package com.vhuomai.wechat.handler;

import com.quanyue.auto.util.GlobalContext;
import com.vhuomai.wechat.constant.MaterialType;
import com.vhuomai.wechat.constant.ReplyEvent;
import com.vhuomai.wechat.entity.BaseWxReply;
import com.vhuomai.wechat.service.WxReplyService;
import com.vhuomai.wechat.support.WxAware;
import com.vhuomai.weixin.common.exception.WxErrorException;
import com.vhuomai.weixin.common.session.WxSessionManager;
import com.vhuomai.weixin.mp.api.WxMpMessageHandler;
import com.vhuomai.weixin.mp.api.WxMpService;
import com.vhuomai.weixin.mp.bean.material.WxMpMaterialVideoInfoResult;
import com.vhuomai.weixin.mp.bean.message.WxMpXmlMessage;
import com.vhuomai.weixin.mp.bean.message.WxMpXmlOutMessage;
import com.vhuomai.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import com.vhuomai.weixin.mp.bean.result.WxMpUser;
import com.vhuomai.weixin.mp.builder.outxml.NewsBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

public class SubscribeHandler implements WxMpMessageHandler {

    @Autowired
    private WxAware wxAware;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WxReplyService replyService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());

        // 获取微信用户基本信息
        WxMpUser wxMpUser = wxMpService.getUserService()
            .userInfo(wxMessage.getFromUser(), null);
        wxAware.onSubscribe(GlobalContext.merchantNo(), wxMpUser);
        try {
            BaseWxReply reply = replyService.findByEvent(ReplyEvent.FOLLOW, ReplyEvent.FOLLOW.name());
            if (reply == null) {
                return WxMpXmlOutMessage.TEXT().content("")
                    .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                    .build();
            } else {
                return this.replyMessage(reply, wxMessage);
            }
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }

    private WxMpXmlOutMessage replyMessage(BaseWxReply reply, WxMpXmlMessage wxMessage) throws WxErrorException {
        if (reply.getContentType() == MaterialType.TEXT) {
            return WxMpXmlOutMessage.TEXT().content(reply.getContent())
                .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                .build();
        } else if (reply.getContentType() == MaterialType.NEWS) {
            return this.findNews(reply, wxMessage);
        } else if (reply.getContentType() == MaterialType.VIDEO) {
            WxMpMaterialVideoInfoResult result = wxMpService.getMaterialService().materialVideoInfo(reply.getMediaId());
            return WxMpXmlOutMessage.VIDEO().mediaId(reply.getMediaId())
                .description(result.getDescription())
                .title(result.getTitle())
                .fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser())
                .build();
        } else if (reply.getContentType() == MaterialType.IMAGE) {
            return WxMpXmlOutMessage.IMAGE().mediaId(reply.getMediaId())
                .fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser())
                .build();
        } else if (reply.getContentType() == MaterialType.VOICE) {
            return WxMpXmlOutMessage.VOICE().mediaId(reply.getMediaId())
                .fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser())
                .build();
        }
        throw new RuntimeException("不支持的类型");
    }

    private WxMpXmlOutMessage findNews(BaseWxReply reply, WxMpXmlMessage wxMessage) throws WxErrorException {
        NewsBuilder builder = WxMpXmlOutMessage.NEWS();
        wxMpService.getMaterialService().materialNewsInfo(reply.getMediaId())
            .getArticles()
            .forEach(article -> {
                WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
                item.setPicUrl(article.getThumbUrl());
                item.setTitle(article.getTitle());
                item.setUrl(article.getUrl());
                item.setDescription(article.getDigest());
                builder.addArticle(item);
            });
        return builder.fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
    }
}
